<!--  -->
<template>
  <div class="app">
    <div class="flex mb-30">
      <div class="btn-back" @click="routerGoTo('MemberDetail')">
        <i class="el-icon-back"></i> 返回
      </div>
      <div class="line"></div>
      <div class="name">编辑学员</div>
    </div>

    <div style="width: 500px">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="200px"
        class="demo-ruleForm"
      >
        <el-form-item label="头像" prop="icon">
          <el-button @click="dialogFormVisible = true">上传图片</el-button>
          <label for="" style="color: #999"
            ><i class="el-icon-info" style="margin: 0 5px 0 15px"></i>建议尺寸:100x100</label
          >
          <div style="width: 100px; height: 100px; margin-top: 15px" v-show="selectUrlFlag">
            <img :src="selectUrl" alt="" style="width: 100px; height: 100px" />
          </div>
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="ruleForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input v-model="ruleForm.passWord"></el-input>
        </el-form-item>

        <el-form-item prop="loginBan">
          <span slot="label">
            登录锁定<i class="el-icon-question" style="margin-left: 5px"></i>
          </span>
          <!-- <label for="delivery" class="el-form-item__label" style="width: 200px;">即时配送<i data-v-41d3103d="" class="el-icon-question"></i></label> -->
          <el-switch v-model="ruleForm.loginBan"></el-switch>
        </el-form-item>
        <el-form-item>
          <span slot="label"> VIP</span>
          <!-- <label for="delivery" class="el-form-item__label" style="width: 200px;">即时配送<i data-v-41d3103d="" class="el-icon-question"></i></label> -->
          <el-select v-model="roleSelect" placeholder="请选择">
            <el-option v-for="item in roles" :key="item.value" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="roleSelect">
          <span slot="label"> VIP到期时间</span>
          <!-- <label for="delivery" class="el-form-item__label" style="width: 200px;">即时配送<i data-v-41d3103d="" class="el-icon-question"></i></label> -->
          <el-date-picker v-model="roleDate" type="date" placeholder="选择日期"> </el-date-picker>
        </el-form-item>
      </el-form>
    </div>

    <div class="footer">
      <el-button type="primary" @click="updataUser">保存</el-button>
      <el-button @click="routerGoTo('MemberDetail')">取消</el-button>
    </div>
    <el-dialog :visible.sync="dialogFormVisible" :show-close="false" width="880px">
      <div slot="title" class="flex flex-spaceBetween">
        <div>选择图片</div>
        <div>
          <el-upload
            class="upload-demo"
            action="http://1.14.239.98/backend/api/v1/media/image"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-error="uploadErr"
            :show-file-list="false"
            multiple
            :limit="3"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :data="sendIcondata"
            :headers="sendIconHeader"
          >
            <el-button>点击上传</el-button>
          </el-upload>
        </div>
      </div>
      <div class="img_list">
        <div
          class="img_item"
          v-for="(item, index) in imgsData"
          :key="index"
          @click.stop="selectImg(item.url, index)"
          :class="{ active: imgIndex == index }"
        >
          <div class="img_box"><img :src="item.url" alt="" /></div>
          <div class="name" v-text="item.name"></div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSelect">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      selectUrl: "",
      imgIndex: "",
      selectUrlFlag: false,
      page: 1,
      size: 18,
      from: 0,
      fileList: [],
      dialogFormVisible: false,
      imgsData: [],
      sendIconHeader: {
        //    'Content-Type': 'application/json'
        Authorization: `Bearer ${localStorage.getItem("admin-token")}`,
      },
      sendIcondata: {
        // disk: "public",
        // encryptData:localStorage.getItem('admin-token'),
        from: 0,
      },
      //   roles: this.$route.params.roles,
      ruleForm: {
        icon: "",
        phone: "",
        name: "",
        passWord: "",
        loginBan: false,

        // selectVip: "",
      },
      rules: {
        name: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        phone: [{ required: true, message: "请输入手机号码", trigger: "blur" }],
        // passWord: [{ required: true, message: "请输入密码", trigger: "blur" }],
        icon: [{ required: true, message: "请输入上传头像", trigger: "blur" }],
      },
      roles: [],
      roleSelect: null,
      roleDate: null,
      userInfo: [],
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    "ruleForm.icon": {
      handler(val, oldvalue) {
        // console.log(val);
        // console.log(oldvalue);
        this.userInfo.avatar = val;
      },
    },
    "ruleForm.phone": {
      handler(val, oldvalue) {
        this.userInfo.mobile = val;
      },
    },
    "ruleForm.name": {
      handler(val, oldvalue) {
        this.userInfo.nick_name = val;
      },
    },
    "ruleForm.passWord": {
      handler(val, oldvalue) {
        this.userInfo.password = val;
      },
    },
    "ruleForm.loginBan": {
      handler(val, oldvalue) {
        this.userInfo.is_lock = val;
      },
    },
    'roleDate' : {
        handler(val, oldvalue) {
        this.userInfo.updated_at = val;
      },
    }
    // ruleForm:{
    //   handler(val,oldval){
    //     console.log(val);
    //     console.log(oldval);
    //     this.userInfo.avatar = val.icon
    //   },
    //   deep:true
    // }
  },
  //方法集合
  methods: {
    confirmSelect() {
      this.selectUrlFlag = true;
      this.dialogFormVisible = false;
      this.ruleForm.icon = this.selectUrl;
    },
    uploadErr(val) {
      // console.log(val);
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    handlePreview(file) {
      // console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}`);
    },
    async getImg() {
      await this.$request
        .get("/media/images", {
          params: {
            page: this.page,
            size: this.size,
            from: this.from,
          },
        })
        .then((res) => {
          // console.log(res);
          this.imgsData = res.data.data.data;
        });
    },
    selectImg(url, _index) {
      // console.log(url);
      this.selectUrl = url;
      this.imgIndex = _index;
    },
    routerGoTo(val) {
      this.$router.push({
        name: val,
      });
    },
    updataUser() {
      let _roleSelect = "";
      let _roleDate = "";
      let password = this.ruleForm.passWord;
      let _userInfo = this.userInfo;
      // if(this.roleSelect){
      //   _roleSelect = '&role_id=' + this.roleSelect;
      //   _roleDate ?  '&role_expired_at=' + this.roleDate.toISOString() : "";
      // }
      let flag = false;
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          // this.$message("添加成功!");
          flag = true;
        } else {
          return this.$message("信息不完整");
        }
      });
      // console.log(this.roleDate.toISOString());
      if (flag) {
        this.$request
          // .put(`/member/${this.$route.params.id}`, {
          //   avatar: this.ruleForm.icon,
          //   is_lock: parseInt(this.ruleForm.loginBan),
          //   mobile: this.ruleForm.phone,
          //   nick_name: this.ruleForm.name,
          //   password,
          //   role_id:this.roleSelect,
          //   // role_expired_at:this.roleDate ? this.roleDate.replace('Z','').replace('T','') : null ,
          //   role_expired_at:this.roleDate ? this.roleDate.toISOString() : null ,
          // })
          .put(`/member/${this.$route.params.id}`, _userInfo)
          .then((res) => {
            if (res.status == 0) {
              this.$message("添加成功!");
              this.firstRender()
            } else {
              this.$message("添加失败!");
            }

            console.log(res);
            // this.selectUrl = "";
            // this.ruleForm.phone = "";
            // this.ruleForm.name = "";
            // this.ruleForm.passWord = "";
            // this.ruleForm.icon="";
            // this.roleSelect = "";
            // this.roleDate = "";
            // this.selectUrlFlag = false;
          })
          .catch((err) => {
            // console.log(err);
          });
      }
    },
   async firstRender(){
       await this.$request.get("/member/" + this.$route.params.id).then((res) => {
      console.log(res);
      this.userInfo = res.data;
      this.ruleForm.icon = res.data.avatar;
      this.selectUrl = res.data.avatar;
      this.selectUrlFlag = true;
      this.ruleForm.name = res.data.nick_name;
      this.ruleForm.phone = res.data.mobile;
      this.ruleForm.loginBan = res.data.is_lock ? true : false;
      this.roleSelect = res.data.role_id;
      this.roleDate = res.data.role_expired_at;
      // this.$forceUpdate()
      //   this.roles = res.data.roles;
    });
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  async created() {
    this.getImg();
    await this.$request.get("/member/create").then((res) => {
      console.log(res);
      this.roles = res.data.roles;
    });
   this.firstRender()
    // console.log(this.$route.params.id);
    // console.log(this.$route.params.roles);
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped lang="less">
.app {
  padding: 30px;
  background-color: white;
  .btn-back {
    &:hover {
      color: #3ca7fa;
      cursor: pointer;
    }
  }
  .mb-30 {
    margin-bottom: 30px;
  }
  .line {
    width: 1px;
    height: 14px;
    background-color: #d8d8d8;
    margin-right: 15px;
    margin-left: 15px;
  }
  .flex {
    width: 100%;
    display: flex;
  }
  .flex-spaceCenter {
    justify-content: center;
  }
  .flex-spaceBetween {
    justify-content: space-between;
  }
  div.img_list {
    width: 100%;
    display: flex;
    justify-content: start;
    flex-wrap: wrap;
    div.img_item {
      width: 110px;
      height: 145px;
      margin: 5px 15px;
      &:hover {
        border: 2px solid #3ca7fa;
        background-color: #d8edfe;
        cursor: pointer;
      }
      .img_box {
        width: 100%;
        height: 110px;
        display: flex;
        align-items: center;
        img {
          width: 100%;
          height: 110px;
        }
      }

      .name {
        width: 110px;
        // height: 15px;
        font-size: 10px;
        font-weight: 400;
        color: #333;
        line-height: 15px;
        text-align: center;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        padding: 10px 5px;
      }
    }
    div.img_item.active {
      border: 2px solid #3ca7fa;
      background-color: #d8edfe;
    }
  }
  .footer {
    position: fixed;
    bottom: 0;
    padding: 20px;
  }
}
</style>
